﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;

namespace _4DJackPot
{
    public partial class CompanyGamesList : Dock
    {
        public CompanyGamesList()
        {
            InitializeComponent();
            dtpFrom.Value = dtpFrom.Value.AddDays(-15);
            dtpTo.Value = dtpFrom.Value.AddDays(+15);

            addCompaniesToPanel();
        }

        private void btnSearch_Click_1(object sender, EventArgs e)
        {
            if (dtpFrom.Value.Date.Ticks > dtpTo.Value.Date.Ticks)
            {
                MessageBox.Show("Enter 'from' earlier than 'to'.");
                return;
            }

            String from = dtpFrom.Value.ToString("yyyy-MM-dd");
            String to = dtpTo.Value.ToString("yyyy-MM-dd");
            ArrayList companies = new ArrayList();
            String companiesString = "";

            // get companies
            foreach (Control c in panelCompanies.Controls)
            {
                if (c is CheckBox)
                {
                    CheckBox cb = (CheckBox)c;
                    if(cb.CheckState == CheckState.Checked)
                    {
                        String companyID = cb.Name.Substring(9);
                        companies.Add(companyID);
                    }
                }
            }
            if (companies.Count == 0)
            {
                MessageBox.Show("Choose company at least one.");
                return;
            }
            else
            {
                companiesString = String.Join(",", companies.ToArray());
            }

            dgvGames.Rows.Clear();

            string selectQueryString =
                "select games.game_id, games.draw_datetime, companies.company_name, Format((select sum(bets.bet_amount) from bets where bets.game_id = games.game_id), 'General Number'), Format((select sum(bet_winnings.bet_winning_amount) from bet_winnings where bet_winnings.bet_id in (select bets.bet_id from bets where bets.game_id = games.game_id)), 'General Number'), company_games.company_id from games, company_games, companies where games.game_id = company_games.game_id and company_games.company_id = companies.company_id and DateValue(games.draw_datetime) >= DateValue('" + from + "') and DateValue(games.draw_datetime) <= DateValue('" + to + "') and company_games.company_id in (" + companiesString + ");";

            Global.dBCmd.CommandText = selectQueryString;
            System.Data.OleDb.OleDbDataReader reader = Global.dBCmd.ExecuteReader(); 
            ArrayList prizeTypes = new ArrayList();
            int i = 0;
            while (reader.Read())
            {
                dgvGames.Rows.Add(1);
                dgvGames["GameID", i].Value = reader[0].ToString();
                dgvGames["DrawDate", i].Value = reader[1].ToString();
                dgvGames["CompanyName", i].Value = reader[2].ToString();
                if (reader[3].ToString().Length == 0)
                    dgvGames["TotalAmount", i].Value = "\\0";
                else
                    dgvGames["TotalAmount", i].Value = "\\" + reader[3].ToString();
                string aaa = reader[4].ToString();
                if (reader[4].ToString().Length == 0)
                    dgvGames["TotalAwardedAmount", i].Value = "\\0";
                else
                    dgvGames["TotalAwardedAmount", i].Value = "\\" + reader[4].ToString();
                dgvGames["Info", i].Value = "Info";
                dgvGames["Split", i].Value = "Split";
                dgvGames["CompanyID", i].Value = reader[5].ToString();

                i++;
            }
            reader.Close();

            if (i == 0)
                MessageBox.Show("There is no games between " + from + " and " + to + ".");
        }

        private void dgvGames_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 5)
            {
                DataGridViewTextBoxCell gameIDCell = (DataGridViewTextBoxCell)dgvGames.Rows[e.RowIndex].Cells[0];
                String gameID = (String)gameIDCell.Value;
                DataGridViewTextBoxCell companyIDCell = (DataGridViewTextBoxCell)dgvGames.Rows[e.RowIndex].Cells[7];
                String companyID = (String)companyIDCell.Value;

                DataGridViewTextBoxCell drawDateCell = (DataGridViewTextBoxCell)dgvGames.Rows[e.RowIndex].Cells[1];
                String drawDate = (String)drawDateCell.Value;

                // If click 'Info' button
                if (e.ColumnIndex == 5)
                {
                    CompanyGameInformation cgiForm = new CompanyGameInformation(gameID, companyID, drawDate);
                    cgiForm.ShowDialog();
                }
                // If click 'Split' button
                else if (e.ColumnIndex == 6)
                {
                    if (DateTime.Parse(drawDate).Date > DateTime.Today.Date)
                    {
                        CompanyGameSplit cgsForm = new CompanyGameSplit(gameID, companyID, drawDate);
                        cgsForm.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("You can change split rate when the game is not drawn.");
                    }
                }
            }
        }

        private void addCompaniesToPanel()
        {
            bool checkDefault = true;
            int width = 170;


            // Get companies list
            string[] companies_id;
            string[] companies_name;
            string[] companies_logo;

            string selectQuery =
                "select company_id, company_name, company_logo_url from companies;";
            DbConn conn = new DbConn();

            DataSet resultReadDataSet = conn.ReadQuery(selectQuery);

            if (resultReadDataSet == null)
            {
                MessageBox.Show("Can`t connect to DB. Please check the DB.", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (resultReadDataSet.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("There are no available companies", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                int len = resultReadDataSet.Tables[0].Rows.Count;
                companies_id = new string[len];
                companies_name = new string[len];
                companies_logo = new string[len];
                int i = 0;
                foreach (DataRow row in resultReadDataSet.Tables[0].Rows)
                {
                    companies_id[i] = row["company_id"].ToString();
                    companies_name[i] = row["company_name"].ToString();
                    companies_logo[i] = row["company_logo_url"].ToString();
                    i++;
                }
            }


            // Add companies to panel
            for (int i = 0; i < companies_id.Length; i++)
            {
                // checkbox
                CheckBox cb = new CheckBox();
                cb.Name = "cbCompany" + companies_id[i];
                cb.Location = new System.Drawing.Point(i * width, 6);
                cb.Checked = checkDefault;
                if (checkDefault)
                    cb.CheckState = CheckState.Checked;
                else
                    cb.CheckState = CheckState.Unchecked;
                cb.Size = new System.Drawing.Size(20, 20);
                panelCompanies.Controls.Add(cb);

                // logo
                PictureBox pb = new PictureBox();
                pb.Image = (Bitmap)global::_4DJackPot.Properties.Resources.ResourceManager.GetObject(companies_logo[i]);
                pb.Location = new System.Drawing.Point(i * width + 20, 0);
                //pb.Name = "pictureBox1";
                pb.Size = new System.Drawing.Size(25, 25);
                pb.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
                panelCompanies.Controls.Add(pb);

                // text
                Label lb = new Label();
                lb.Location = new System.Drawing.Point(i * width + 48, 10);
                lb.Text = companies_name[i];
                panelCompanies.Controls.Add(lb);
            }
        }
    }
}
